import { Component } from 'react';
import Taro from '@tarojs/taro';
import { View, Image, Button } from '@tarojs/components'
import { staticUrl } from '@/utils'
import classnames from 'classnames'
import map from '@/utils/map'
import './index.scss'

import { getPlatformGoodsDetails } from '@/api/goods/details'
import { getSkuInfo, createCart } from '@/api/goods'
import { getOrderDefaultStore } from '@/api/cheap'

const typeIcon1 = staticUrl('/img/cheap/type_1.png')
const typeIcon2 = staticUrl('/img/cheap/type_2.png')
const priceIcon = staticUrl('/img/cheap/t_8.png')

interface State {
  goods: Object,
  detailsImg: String,
  shareData: Object,
  userLongitude: any
  userLatitude: any,
  selectStore: Object,
  jihuasuanId: any,
  storeCode?: String,
  pMobile?: any,
  ppMobile?: any,
  pUnionId?: any,
  ppUnionId?: any,
  index?: any,
  thirdPartyShareSource?: any,//集划算推广来源
}

export default class GoodsItem extends Component<any, State> {
  constructor (props) {
    super(...arguments)
    this.state = {
      goods: props.goods,
      detailsImg: props.detailsImg,
      shareData: props.shareData,
      userLongitude: 0,
      userLatitude: 0,
      selectStore: {},
      jihuasuanId: null,
      storeCode: '', //黑盒分享门店编码
      pMobile: '',//一级分销员
      ppMobile: '',//二级分销员
      pUnionId: '',
      ppUnionId: '',
      index: 0,
      thirdPartyShareSource: ''
    }
  }

  async componentDidMount() {
    console.log('执行了吗----topic', this.props)
    this.getLocation()
    const { storeCode, jihuasuanId, goods, pMobile, ppMobile, index, pUnionId, ppUnionId, thirdPartyShareSource } = this.props
    this.setState({
      storeCode,
      jihuasuanId: jihuasuanId ? jihuasuanId : goods.jihuasuanId,
      pMobile,
      ppMobile,
      pUnionId,
      ppUnionId,
      index,
      thirdPartyShareSource
    })
  }

  /**
   * 获取当前位置
   */
  async getLocation() {
    let locationData = Taro.getStorageSync('CURRENT_LONGITUDE_LATITUDE')
    if (locationData) {
      const { latitude: userLatitude, longitude: userLongitude } = locationData
      this.setState({
        userLongitude,
        userLatitude
      })
    } else {
      if (process.env.TARO_ENV === 'weapp') {
        const curLocation: any = await map.getLocation()
        if (curLocation) {
          const { latitude: userLatitude, longitude: userLongitude } = curLocation
          this.setState({
            userLongitude,
            userLatitude
          })
        }
      }
    }
  }

  /**
   * 获取下单门店
   */
  getOrderDefaultStore() {
    const { userLongitude, userLatitude, goods, jihuasuanId, shareData } = this.state
    let {
      storeCode = ''
    } = shareData

    console.log('this.state', this.state)
    let params = {
      userLongitude,
      userLatitude,
      type: goods.type,
      jihuasuanId: jihuasuanId,
      goodsIds: goods.referId,
      jihuasuanSource: storeCode ? 1 : 0,
      storeCode: storeCode ? storeCode : undefined
    }
    getOrderDefaultStore(params).then(res => {
      const data = res.data.data
      this.setState({
        selectStore: {
          storeCode: data.store.storeCode,
          storeName: data.store.storeName,
          cityCode: data.store.cityCode,
        }
      }, () => {
        if (goods.type == 1) { //商品
          this.getPlatformGoodsDetails()
        } else { //年卡
          this.createAnnual()
        }
      })
    })
  }

  /**
   * 获取商品详情
   */
  getPlatformGoodsDetails() {
    let { goods, jihuasuanId } = this.state
    getPlatformGoodsDetails({
      goodsId: goods.referId,
      fields: 'id,skuInfo.*',
    }).then(res => {

      let data = res.data.data
      this.getPlatformGoodsSku({
        jihuasuanGoodsId: goods.id,
        jihuasuanId: jihuasuanId,
        goodsId: goods.referId,
        skuItemIds: data.skuInfo[0].items[0].id
      })
    })
  }

  /**
   * 获取sku
   */
  getPlatformGoodsSku(params) {
    getSkuInfo(params).then(res => {
      let data = res.data.data
      if (!data.stock && data.stockTips) {
        Taro.showToast(res.data.stockTips)
        return
      }
      let { goods, selectStore } = this.state
      let params = {
        goodsData: JSON.stringify([{
          goodsId: goods.referId,
          goodsSkuId: data.goodsSkuId,
          number: 1,
          itemType: 1,
          directBuy: 1
        }]),
        storeCode: selectStore.storeCode
      }
      this.createCart(params)
    })
  }
  /**
   * 加购物车
   */
  createCart(params) {
    const { goods, selectStore, storeCode, jihuasuanId, shareData } = this.state
    let { pMobile = '', ppMobile = '', pUnionId = '', ppUnionId = '', thirdPartyShareSource = '' } = shareData
    createCart(params).then(res => {
      let data = res.data.data
      Taro.navigateTo({
        url: `/pages/order/index/index?cartIds=${JSON.stringify(data.cartIds)}&store=${JSON.stringify(selectStore)}&jihuasuanId=${jihuasuanId}&pMobile=${pMobile}&ppMobile=${ppMobile}&jihuasuanGoodsId=${goods.id}&jihuasuanSource=${storeCode ? 1 : 0}&pUnionId=${pUnionId}&ppUnionId=${ppUnionId}&thirdPartyShareSource=${thirdPartyShareSource}`
      })
    })
  }

  /**
   * 年卡下单
   */
  createAnnual() {
    const { goods, selectStore, storeCode, jihuasuanId, shareData } = this.state
    let { pMobile = '', ppMobile = '', pUnionId = '', ppUnionId = '', thirdPartyShareSource = '' } = shareData
    Taro.navigateTo({
      url: `/pages/order/index/index?annualCardId=${goods.referId}&type=1&jihuasuanId=${jihuasuanId}&pMobile=${pMobile}&ppMobile=${ppMobile}&jihuasuanGoodsId=${goods.id}&jihuasuanSource=${storeCode ? 1 : 0}${selectStore.storeCode ? `&storeCode=${selectStore.storeCode}` : ''}&pUnionId=${pUnionId}&ppUnionId=${ppUnionId}&thirdPartyShareSource=${thirdPartyShareSource}`
    })
  }

  /**
   * 立即购买
   */
  gotoOrder(e) {
    e.stopPropagation()
    console.log('this', this)
    Taro.showLoading({
      title: "加载中...",
      mask: true
    })
    let { goods } = this.state
    this.getOrderDefaultStore()
  }

  /**
   * 分享朋友圈
   */
  handlePoster = (e) => {
    e.stopPropagation()
    let { goods, shareData } = this.state
    let { jihuasuanId } = goods
    console.log('shareData', shareData)
    let { pMobile, pUnionId } = shareData

    let query = {
      jihuasuanId: jihuasuanId,
      indirectShareMobile: pMobile || pUnionId,//间接分销
    }
    Taro.navigateTo({ url: `/pages/webview/index/index?path=${'/cheap/poster'}&query=${JSON.stringify(query)}` })
  }

  render() {
    const { goods, detailsImg, index } = this.state
    if (goods.discount) {
      goods.discount = parseFloat(goods.discount)
    }
    if (goods.pCanReward) {
      goods.pCanReward = parseFloat(goods.pCanReward)
    }
    return (
      <View className='goods-item'>
        <View
          className={
            classnames('thumb-img', {
              'esp-thumb-img': detailsImg
            })
          }>
          {
            !detailsImg ? <Image className='type-icon' src={goods.type == 1 ? typeIcon1 : typeIcon2} /> : null
          }
          <Image className='image' src={detailsImg || goods.referUploadUrl} mode="widthFix" />
        </View>
        <View className='info-wrap-esp'>
          <View className='info'>
            <View className='buy'>
              <View className='left'>
                <Image className='icon' src={priceIcon}></Image>
                现在下单约省￥{goods.discount}
              </View>
              <View className="btn" onClick={(e) => this.gotoOrder(e)}>立即抢购</View>
            </View>
            <View className="share">
              <View className="price">
                {
                  Number(goods.pCanReward) ? <View>
                    <View className="label">分享赚</View>
                    <View className="num">￥{goods.pCanReward}</View></View> : null
                }
              </View>
              <View className='rbtn'>
                <View className="btn share1" onClick={(e) => this.handlePoster(e)}>分享朋友圈赚钱</View>
                <Button onClick={(e) => { e.stopPropagation() }} openType="share" id={goods.id} data-index={index} className="btn share2">分享给好友赚钱</Button>
              </View>
            </View>
          </View >
        </View>
      </View >
    )
  }
}
